package com.onlineauction.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.onlineauction.entities.Auction;
import com.onlineauction.entities.User;
import com.onlineauction.exceptions.WrongPasswordException;
import com.onlineauction.helpers.Constants;

public class LoginAccountServlet extends HttpServlet {
	
	private static final long serialVersionUID = 6847848537208167207L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,
			ServletException {

		String username = request.getParameter(Constants.USERNAME);
		String password = request.getParameter(Constants.PASSWORD);
				
		if (username == null || password == null) {					
			request.getRequestDispatcher("/login.jsp").forward(request, response);
			return;
		}
		
		if ( (username != null && password != null) && (username.length() == 0 || password.length() == 0)) {
			String message = "Username and password cannot be empty.";
			request.setAttribute(Constants.MESSAGE, message);
			request.getRequestDispatcher("/login.jsp").forward(request, response);
			return;
		}
		
		User user = null;
		try {
			user = new User(username, password);
		} catch (WrongPasswordException e) {
			user = null;
		}
		if (user == null) {
			String message = "Username and password do not match!";
			request.setAttribute(Constants.MESSAGE, message);
			request.getRequestDispatcher("/login.jsp").forward(request, response);
			return;
		} else {		
			Auction.markExpiredAuctions();
			request.getSession(true).setAttribute(Constants.USERNAME, user.getUsername());			
			response.sendRedirect("/Home");
		}
		
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		doGet(request, response);
	}

}
